package com.ext.aic.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;

import com.ext.aic.R;
import com.ext.aic.constants.PermissionConstants;
import com.ext.aic.databinding.AiSeparateSettingLayoutBinding;
import com.ext.aic.handler.ActivityResultHandler;
import com.ext.aic.utils.BoxUtils;
import com.ext.aic.utils.PermissionUtils;
import com.eyinfo.android_pure_utils.ebus.EBus;
import com.eyinfo.android_pure_utils.events.Action1;
import com.yanzhenjie.permission.AndPermission;

import java.text.MessageFormat;

public class AISeparateSettingActivity extends BaseActivity {
    private AiSeparateSettingLayoutBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = View.inflate(this, R.layout.ai_separate_setting_layout, null);
        binding = AiSeparateSettingLayoutBinding.bind(view);
        setContentView(binding.getRoot());
        bindView();
        initData();
    }

    private void bindView() {
        binding.topView.backIv.setOnClickListener(v -> finish());
        String appName = getString(R.string.app_name);
        String title = getString(R.string.ai_separate_setting_title);
        binding.topView.titleTv.setText(MessageFormat.format("{0}{1}", appName, title));
        binding.accessibilitySwitchSb.setOnCheckedChangeListener(this::onAccessibilitySwitchListener);
        binding.notificationSwitchSb.setOnCheckedChangeListener(this::onNotificationSwitchListener);
        binding.turnOffBackgroundRestrictedSwitchSb.setOnCheckedChangeListener(this::onBackgroundRestrictedSwitchListener);
    }

    private void initData() {
        EBus.getInstance().registered(this);
        activityResultHandler.onCreate(this);
        binding.accessibilitySwitchSb.setChecked(PermissionUtils.getInstance().isAccessibilityServiceEnabled(this));
        binding.notificationSwitchSb.setChecked(PermissionUtils.getInstance().isNotificationEnabled(this));
        binding.turnOffBackgroundRestrictedSwitchSb.setChecked(PermissionUtils.getInstance().isBackgroundRestricted(this));
        if (PermissionUtils.getInstance().hasBatteryOptimizationSetting(this)) {
            binding.turnOffBackgroundRestrictedSwitchLl.setVisibility(View.VISIBLE);
        }
    }

    public void onAccessibilitySwitchListener(CompoundButton buttonView, boolean isChecked) {
        if (PermissionUtils.getInstance().isAccessibilityServiceEnabled(this)) {
            binding.accessibilitySwitchSb.setChecked(isChecked);
        } else {
            if (isChecked) {
//                EBus.getInstance().post(EBusConstants.enableAccessibilityFeature);
                BoxUtils.getInstance().enableAccessibilityFeature(this, new Action1<String>() {
                    @Override
                    public void call(String autoReplyTag) {
                        Intent intent = PermissionUtils.getInstance().getAccessibilitySettingsIntent(autoReplyTag);
                        activityResultHandler.startActivityForResult(AISeparateSettingActivity.this, intent, PermissionConstants.REQUEST_CODE_ACCESSIBILITY);
                    }
                });
            } else {
                binding.accessibilitySwitchSb.setChecked(false);
            }
        }
    }

    public void onNotificationSwitchListener(CompoundButton buttonView, boolean isChecked) {
        AndPermission.with(this)
                .runtime()
                .setting()
                .start(100);
        //POST_NOTIFICATIONS
//        AndPermission.with(this)
//                .runtime()
//                .permission("android.permission.POST_NOTIFICATIONS")
//                .rationale((context, data, executor) -> {
//                    System.out.println("解释为何需要权限");
//                })
//                .onGranted(permissions -> {
//                    System.out.println("授权成功");
//                })
//                .onDenied(permissions -> {
//                    // 被拒绝
//                    if (AndPermission.hasAlwaysDeniedPermission(this, permissions)) {
//                        // 用户勾选了"不再询问"，引导至设置页
//                        System.out.println("用户勾选了\"不再询问\"，引导至设置页");
//                    } else {
//                        System.out.println("权限被拒绝");
//                    }
//                })
//                .start();
//        if (PermissionUtils.getInstance().isNotificationEnabled(this)) {
//            binding.notificationSwitchSb.setChecked(isChecked);
//        } else {
//            if (isChecked) {
//                BoxUtils.getInstance().enableNotificationFeature(this, new Action1<String>() {
//                    @Override
//                    public void call(String autoReplyTag) {
//                        Intent intent = PermissionUtils.getInstance().getNotificationSettings(autoReplyTag);
//                        activityResultHandler.startActivityForResult(AISeparateSettingActivity.this, intent, PermissionConstants.REQUEST_CODE_NOTIFICATION);
//                    }
//                });
//            } else {
//                binding.notificationSwitchSb.setChecked(false);
//            }
//        }
    }

    public void onBackgroundRestrictedSwitchListener(CompoundButton buttonView, boolean isChecked) {
        if (PermissionUtils.getInstance().isBackgroundRestricted(this)) {
            binding.turnOffBackgroundRestrictedSwitchSb.setChecked(isChecked);
        } else {
            if (isChecked) {
                BoxUtils.getInstance().enableRestrictedFeature(this, new Action1<String>() {
                    @Override
                    public void call(String autoReplyTag) {
                        Intent intent = PermissionUtils.getInstance().getRestrictedSettingIntent(autoReplyTag);
                        activityResultHandler.startActivityForResult(AISeparateSettingActivity.this, intent, PermissionConstants.REQUEST_CODE_BACKGROUND_RESTRICTED);
                    }
                });
            } else {
                binding.turnOffBackgroundRestrictedSwitchSb.setChecked(false);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        activityResultHandler.onActivityResult(requestCode, resultCode, data);
    }

    private ActivityResultHandler activityResultHandler = new ActivityResultHandler() {

        @Override
        protected void onFinallyResult(Bundle bundle) {
            BoxUtils.getInstance().onAutoReplyActivityResult(AISeparateSettingActivity.this, bundle);
            binding.accessibilitySwitchSb.setChecked(PermissionUtils.getInstance().isAccessibilityServiceEnabled(AISeparateSettingActivity.this));
            binding.notificationSwitchSb.setChecked(PermissionUtils.getInstance().isNotificationEnabled(AISeparateSettingActivity.this));
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        activityResultHandler.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        activityResultHandler.onPause();
    }
}
